//
//  File.swift
//  OnemeetingDemo
//
//  Created by 张衡 on 2020/4/10.
//  Copyright © 2020 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation

class File: NSObject {
    
    static var chatURL:URL {
        let url = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)[0]
        return url
    }
    
    static var contents:String = "onemeeting"
    
    static var _chatFileName:String?
    static var chatFileName:String {
        guard let fileName = _chatFileName else {
            let time = PE.timeNow(dateFormat: "yyyyMMddHHmmss")
            let fileName = "onemeeting_chat_"+time+".txt"
            _chatFileName = fileName
            return fileName
        }
        return fileName
    }
    
    class func isfileExists(path:String) -> Bool{
        let  fileManager = FileManager.default
        let result = fileManager.fileExists(atPath: path)

        if result {
            return true
        }else{
            return false
        }
    }

    class func creatFilePath(path:String) {
        let  fileManager = FileManager.default
        do{
            // 创建文件夹   1，路径 2 是否补全中间的路劲 3 属性
            try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)

            //创建文件    1 路径  2 内容 3 属性
            //try fileManager.createFile(atPath: path, contents: nil, attributes: nil)
        } catch{
            print("creat false")
        }
    }

    class func removeFilePath(path:String){
        let  fileManager = FileManager.default
        do{
            try fileManager.removeItem(atPath: path)
        } catch{
            print("creat false")
        }
    }
    
    
    class func readFileContents(url:String) -> [String] {
        let dict = try? FileManager.default.contentsOfDirectory(atPath: url)
        return dict ?? []
    }

    //根据文件名和路径创建文件
    class func createFile(name:String,contents:String?,txt:String,fileBaseUrl:URL){
        let manager = FileManager.default
        
        if let fileContents = contents {
            let filePath = fileBaseUrl.appendingPathComponent(fileContents)
            self.creatFilePath(path: filePath.path)
        }
        
        let file = contents==nil ? fileBaseUrl.appendingPathComponent(name):fileBaseUrl.appendingPathComponent(contents!+"/"+name)
        print("文件: \(file)")
        let exist = manager.fileExists(atPath: file.path)
        if !exist {
            //在文件中随便写入一些内容
            let data = txt.data(using: String.Encoding.utf8)
            let createSuccess = manager.createFile(atPath: file.path,contents:data!,attributes:nil)
            print("文件创建结果: \(createSuccess)")
        }else {
            self.removeFilePath(path: file.path)
            self.createFile(name: name, contents: contents, txt: txt, fileBaseUrl: fileBaseUrl)
        }
    }

    
    func writeDataToFile() {
        let fileUrl = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)[0]
        let fileName = "chat"+"time"+".txt"
        let nfHandle = FileHandle.init(forUpdatingAtPath: (fileUrl.path)+"/"+fileName)
        
        // 文件句柄偏移量
        // 获取文件句柄指针的偏移量
        let offSetNum1:UInt64 = nfHandle!.offsetInFile
        // 将偏移量移到文件末尾，返回移动后的指针偏移量
        let offSetNum2:UInt64 = nfHandle!.seekToEndOfFile()
        // 将偏移量指向特定的位置
        nfHandle!.seek(toFileOffset: 0)
        
        // 从当前指针位置写入数据到文件
        let newData =  "你好".data(using: String.Encoding.utf8, allowLossyConversion: true)
        nfHandle?.write(newData!)
            
        // 文件关闭
        nfHandle?.closeFile()
        
    }
    
    
    
}
